package com.ruoyi.common.utils.file;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 文件上车实现类 byte 数组格式转换 MultipartFile
 *
 * @author yuanqinglong
 * @data 2024-05-23
 */
public class MultipartFileImpl implements MultipartFile {
    /**
     * 文件数据
     */
    private byte[] bytes;
    /**
     * 文件名称
     */
    private String name;

    /**
     * 构建 byte 数组为 MultipartFile 类型
     *
     * @param bytes 文件数据
     * @param name  文件名称
     */
    public MultipartFileImpl(byte[] bytes, String name) {
        this.bytes = bytes;
        this.name = name;
    }

    private MultipartFileImpl() {

    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return this.name;
    }

    @Override
    public String getContentType() {
        return FileUtils.getNameNotSuffix(this.name);
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public long getSize() {
        return this.bytes.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return this.bytes;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.bytes);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        FileOutputStream stream = new FileOutputStream(dest);
        stream.write(this.bytes);
        stream.flush();
        stream.close();
    }
}
